<template>
  <div class="upload">
    <!-- 单图片上传 -->
    <template v-if="mode === 1">
      <el-upload v-loading="loading" :disabled="disabled" style="width: 150px;padding-top: 5px;"
        class="avatar-uploader mode_1" :action="action" :show-file-list="false" :before-upload="handleBefore"
        :on-error="handleSuccess" :on-success="handleSuccess" :headers="headers">
        <img v-if="mode_1.imageUrl" :src="mode_1.imageUrl" class="avatar" @click="showImage(mode_1.imageUrl)">
        <i v-else class="el-icon-plus avatar-uploader-icon" />
        <div slot="tip" class="el-upload__tip">{{ tip }}</div>
      </el-upload>
    </template>
    <!-- 文件上传 -->
    <template v-if="mode === 2">
      <el-upload v-loading="loading" class="upload-demo" :action="action" :on-preview="handlePreview"
        :before-upload="handleBefore" :on-error="handleSuccess" :on-success="handleSuccess" :limit="mode_2.limit"
        :file-list="mode_2.fileList" :headers="headers">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </template>
    <!-- 上传 视频 -->
    <template v-if="mode === 7">
      <div class="wrapper">
        <div class="wrapper">
          <el-upload class="avatar-uploader mode_1" :action="action" :headers="headers" :on-progress="uploadVideoProcess"
            :on-success="handleVideoSuccess" :before-upload="beforeUploadVideo" :show-file-list="false">
            <video v-if="videoForm.showVideoPath && !videoFlag" style="width:300px;height:150px;"
              :src="videoForm.showVideoPath" class="avatar video-avatar" controls="controls">您的浏览器不支持视频播放</video>
            <i v-else-if="!videoForm.showVideoPath && !videoFlag" class="el-icon-plus avatar-uploader-icon" />
            <el-progress v-if="videoFlag === true" type="circle" :percentage="videoUploadPercent" style="margin-top:7px;" />
          </el-upload>
          <el-button style="margin-left: 10px; height: 33px;" v-if="videoForm.showVideoPath && !videoFlag" size="small" type="danger" @click="removeVideo">移除视频</el-button>
        </div>
      </div>
    </template>
    <!-- 单文件导入 -->
    <template v-if="mode === 3">
      <el-upload v-loading="loading" class="upload-demo" :action="action" :auto-upload="false" :on-change="handleChange"
        :before-upload="handleBefore" :on-error="handleSuccess" :on-success="handleSuccess" :show-file-list="false">
        <el-button size="small" type="primary">点击上传</el-button>
        <span v-if="showFileName">{{ showFileName }}</span>
      </el-upload>
    </template>
    <!-- 多文件上传 -->
    <template v-if="mode === 4">
      <el-upload v-loading="loading" class="upload-demo" :headers="headers" :action="action" :on-preview="handlePreview"
        :before-upload="handleBefore" :on-remove="handleRemove" :on-error="handleSuccess" :on-success="handleSuccess"
        multiple>
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </template>

    <!-- 多图片上传 -->
    <template v-if="mode === 5">
      <div class="list-img">
        <!-- <img
          v-for="(item, index) in mode_5.fileList"
          :key="index"
          v-show="item.url"
          :src="item.url"
          class="avatar"
          @click="showImage(item.url)"
        />-->

        <el-upload v-loading="loading" :disabled="disabled" style="padding-top: 5px;" class="avatar-uploader mode_5"
          :action="action" :headers="headers" :limit="mode_5.limit" :show-file-list="true" :before-upload="handleBefore"
          :on-remove="handleRemove" :on-error="handleSuccess" :on-success="handleSuccess" :file-list="mode_5.fileList"
          list-type="picture-card">
          <i class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
        <div class="el-upload__tip" style="line-height: 16px;">{{ tip }}</div>
      </div>
    </template>
    <!-- 单图片按钮上传,放大预览 -->
    <template v-if="mode === 6">
      <div class="upImgToBigBox">
        <el-upload v-loading="loading" :disabled="disabled" style="width: 150px;padding-top: 5px;" class="upload-demo"
          :action="action" :show-file-list="false" :before-upload="handleBefore" :on-error="handleSuccess"
          :on-success="handleSuccess" :headers="headers">
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
        <div class="demo-image__preview" v-if="mode_1.imageUrl" title="点击图片查看大图">
          <el-image style="width: 100px; height: 100px" :src="mode_1.imageUrl" :preview-src-list="[mode_1.imageUrl]">
          </el-image>
        </div>
        <!-- <span v-if="mode_1.imageUrl" style="margin-left:30px;margin-top:40px;color:#ff8704;">点击图片查看大图</span> -->
      </div>
    </template>
    <!-- 上传单个Excel -->
    <template v-if="mode === 8">
      <el-upload v-loading="loading" class="upload-demo" :action="action" accept=".xlsx" :limit="1" :on-change="handleChange"
        :before-upload="handleBefore" :on-error="handleSuccess" :on-success="handleSuccess">
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
    </template>

    <el-dialog title="预览" :close-on-click-modal="false" :visible.sync="imageVisible" width="600px">
      <div style="text-align:center;">
        <img style="max-width: 100%;" :src="showImageUrl" alt>
      </div>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="imageVisible = false">关闭</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { BASEURL } from '../../../public/static/config'
import { getToken } from "@/utils/auth";

export default {
  props: {
    mode: {
      type: Number,
      default: 1
    },
    defaultImage: {
      type: String,
      default: ''
    },
    tip: {
      default: '',
      type: String
    },
    defaultFile: {
      default: '',
      type: String
    },
    importUrl: {
      default: '',
      type: String
    },
    disabled: {
      default: false,
      type: Boolean
    },
    defaultVideo: {
      default: '',
      type: String
    },
    defaultFileName: {
      default: '',
      type: String
    },
    size: {
      default: 0,
      type: Number
    },
    validWidth: {
      default: 0,
      type: Number
    },
    validHeight: {
      default: 0,
      type: Number
    }
  },
  data() {
    return {
      action: (process.env.BASE_URL || BASEURL) + '/common/oss/single',
      mode_1: {
        imageUrl: ''
      },
      loading: false,
      imageVisible: false,

      mode_2: {
        fileList: [],
        limit: 1
      },
      mode_5: {
        fileList: [],
        limit: 5
      },
      // 多文件上传
      mode_4: {
        fileList: []
      },
      // 一次上传的文件个数
      uploadNumber: 0,
      // 已上传完成文件个数
      alreadyNumber: 0,
      showImageUrl: '',
      videoFlag: false,
      // 是否显示进度条
      videoUploadPercent: '',
      // 进度条的进度，
      isShowUploadVideo: false,
      // 显示上传按钮
      videoForm: {
        showVideoPath: ''
      },
      showFileName: '',
      headers: {
        // token: this.$store.state.user.token
        token: getToken()
      }
    }
  },
  watch: {
    defaultImage: {
      immediate: true,
      handler(val) {
        if (this.mode === 1 || this.mode === 6) {
          this.mode_1.imageUrl = val
        }
        if (this.mode === 5) {
          this.mode_5.fileList = val
        }
      }
    },
    defaultFile: {
      immediate: true,
      handler(val) {
        if (val) {
          this.mode_2.fileList = [
            {
              name: val,
              uid: '',
              url: val
            }
          ]
        } else {
          this.mode_2.fileList = []
        }
      }
    },
    defaultVideo: {
      immediate: true,
      handler(val) {
        if (val) {
          this.videoForm.showVideoPath = val
        } else {
          this.videoForm.showVideoPath = ''
        }
      }
    },
    defaultFileName: {
      immediate: true,
      handler(val) {
        if (val) {
          this.showFileName = val
        } else {
          this.showFileName = ''
        }
      }
    }
  },
  created() {
    if (this.mode === 3) {
      this.action = process.env.BASE_URL + this.importUrl
    }
    if (this.mode === 7) {
      this.action = (process.env.BASE_URL || BASEURL) + '/dinner/product/pc/uploadVideo'
    }
  },
  methods: {
    handlePreview(file) {
      window.open(file.url, '_blank')
      // console.log(file);
    },
    handleBefore(file, files) {
      if (this.size > 0) {
        const fileSize = file.size / 1024 / 1024 < this.size
        if (!fileSize) {
          this.$message.error('文件大小不能超过' + this.size + 'MB')
          return false
        }
      }
      if (
        (this.mode === 1 || this.mode === 6) &&
        ['image/jpeg', 'image/gif', 'image/png', 'image/bmp'].indexOf(
          file.type
        ) === -1
      ) {
        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式')
        return false
      }
      // 如果要验证宽高
      // this.validWidth  由上级组件传入 props 接收
      // this.validHeight 由上级组件传入 props 接收
      if ((this.mode === 1 || this.mode === 6) && this.validWidth && this.validHeight) {
        // console.log(this.valWidthAndHeight(file));
        var _this = this
        return new Promise(function (resolve, reject) {
          var reader = new FileReader()
          reader.onload = function (event) {
            var image = new Image()
            image.onload = function () {
              var width = this.width
              var height = this.height
              if (width != _this.validWidth || height != _this.validHeight) {
                _this.$alert(
                  '图片宽高必须等于' +
                  _this.validWidth +
                  'px*' +
                  _this.validHeight +
                  'px！',
                  '提示',
                  {
                    confirmButtonText: '确定'
                  }
                )
                reject()
              }
              resolve()
            }
            image.src = event.target.result
          }
          reader.readAsDataURL(file)
        })
      }
    },
    handleSuccess(res, file) {
      this.loading = false
      if (res && res.code === 200) {
        this.handleMode(res.result, file)
      } else {
        this.$message.error(res.message)
      }
      // this.mode_1.imageUrl = URL.createObjectURL(file.raw);
    },
    handleRemove(file, files) {
      console.log(file, files)
      if (this.mode === 4) {
        this.mode_4.fileList = this.mode_4.fileList.filter((item) => {
          return item.uid !== file.uid
        })
      } else if (this.mode === 5) {
        console.log(files)
        // this.mode_5.fileList = this.mode_5.fileList.filter(item => {
        //   return item.uid !== file.uid
        // })
        this.$emit('update:defaultImage', files)
      }
    },
    handleChange(file, fileList) {
      if (this.mode === 3) {
        this.videoForm.showVideoPath = file.raw.name
        // 导入
        this.$emit('change', file.raw)
      }
    },
    handleMode(res, file) {
      if (this.mode === 1 || this.mode === 6) {
        this.mode_1.imageUrl = res
        this.$emit('update:defaultImage', res)
        // this.$emit('uploadSuccess', res)
      } else if (this.mode === 4) {
        file.url = res
        this.mode_4.fileList.push(file)
        this.alreadyNumber++
        this.$emit('uploadSuccess', {
          uploadNumber: this.uploadNumber,
          alreadyNumber: this.alreadyNumber
        })
        if (this.alreadyNumber === this.uploadNumber) {
          this.uploadNumber = 0
          this.alreadyNumber = 0
        }
        return
      } else if (this.mode === 5) {
        this.mode_5.fileList.push({
          name: file.name,
          url: res,
          uid: file.uid
        })
        this.$emit('update:defaultImage', this.mode_5.fileList)
      } else if (this.mode === 7) {
        this.$emit('update:defaultVideo', res)
      } else if (this.mode === 3 || this.mode === 2) {
        this.$emit('update:defaultFileName', res)
      }
    },
    showImage(url) {
      if (this.disabled) {
        this.imageVisible = true
        this.showImageUrl = url
      }
    },
    deleteList() {
      if (this.mode_2.fileList.length > 0) {
        this.mode_2.fileList = []
      }
    },
    // 上传前回调
    beforeUploadVideo(file) {
      return new Promise(async (resolve, reject) => {
        var fileSize = file.size / 1024 / 1024 < 200
        if (
          [
            'video/mp4',
            'video/ogg',
            'video/flv',
            'video/avi',
            'video/wmv',
            'video/rmvb',
            'video/mov'
          ].indexOf(file.type) === -1
        ) {
          this.$message.error('请上传正确的视频格式')
          reject()
          return false
        }
        if (!fileSize) {
          this.$message.error('视频大小不能超过200MB')
          reject()
          return false
        }
        
        let audioLength = await this.checkVideoLength(file)
        if (audioLength > 30) {
          this.$message.error('视频长度不能超过30秒')
          reject()
          return false
        }
        this.isShowUploadVideo = false
        resolve()
      })
    },
    // 进度条
    uploadVideoProcess(event, file, fileList) {
      this.videoFlag = true
      this.videoUploadPercent = file.percentage.toFixed(0) * 1
    },
    // 上传成功回调
    handleVideoSuccess(res, file) {
      this.isShowUploadVideo = true
      this.videoFlag = false
      this.videoUploadPercent = 0
      // 后台上传地址
      if (res.code === 200) {
        this.videoForm.showVideoPath = res.result
        this.handleMode(res.result, file)
      } else {
        this.$message.error(res.message)
      }
    },
    removeVideo() {
      this.videoForm.showVideoPath = ''
      this.$emit('update:defaultVideo', '')
      this.videoFlag = false
      this.videoUploadPercent = 0
    },
    checkVideoLength(file) {
      return new Promise((resolve) => {
        var binaryData = []
        binaryData.push(file)
        var fileUrl = URL.createObjectURL(new Blob(binaryData));
        var audio = new Audio(fileUrl)
        audio.addEventListener("loadedmetadata", function() {
          resolve(audio.duration)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader.mode_1 {
  line-height: 12px;
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
}
.list-img {
  display: flex;
  flex-direction: column;
  img {
    width: 120px;
    height: 120px;
    margin-right: 10px;
    cursor: pointer;
    border-radius: 6px;
  }
}
.el-upload-list--picture-card {
  display: flex !important;
}
.mode_5 {
  display: flex;
}
.upImgToBigBox {
  display: flex;
  align-items: flex-start;
  width: 100%;
  .el-image-viewer__btn {
    color: #fff;
  }
}

  .wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
